/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2022 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "cmsis_os.h"
#include "dma.h"
#include "tim.h"
#include "usart.h"
#include "usb_device.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "BTK05.h"
#include "KeyBoard.h"
#include "usbd_customhid.h"
#include "RGB.h"
#include "string.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
uint32_t sleepTime1SCounter = 0;

volatile uint16_t tim8_counter = 0;
volatile uint16_t tim7_counter = 0;

unsigned char sleepTime50MsCounter = 0;
unsigned char LED_breath_Flag = 0;
unsigned char LED_LOGOBreath_Flag = 0;
unsigned char LED_LOGOENBreath_Flag = 0;
unsigned char system_Status = 1;

unsigned char USB_Receive_Buffer[64];
unsigned char USB_Received_Count = 0;

uint8_t blank[8] = {0,0,0,0,0,0,0,0};

uint8_t Send_1[8] = {1,0,6,0,0,0,0,0};
uint8_t Send_2[8] = {1,0,25,0,0,0,0,0};

uint8_t Control_Code[8] = {0,0,0,0,0,0,0,0};
uint8_t Control_ID;
uint8_t Control_BUTTON = 0;

uint8_t Common_Code[6] = {0,0,0,0,0,0};
uint8_t Common_ID;

uint8_t Blue_tooth_Buffer[12] =
{
	BTK05_CMD_BYTE1 ,
	BTK05_CMD_BYTE2 ,
	BTK05_CMD_BYTE3 ,
	BTK05_CMD_BYTE4 ,
	0x00 ,
	0x00 ,
	0x00 ,
	0x00 ,
	0x00 ,
	0x00 ,
	0x00 ,
	0x00
};

uint8_t count_time_1s_right = 0;
uint8_t count_time_1s_left = 0;

uint8_t Light_Flag = 0;

uint8_t Right_Flag = UNACTIVATED;
uint8_t Left_Flag= UNACTIVATED;
uint8_t Pre_flag = 0;

uint8_t Hong_Light = 0;
uint8_t Hong_Pre_flag = 0;

uint8_t bDeviceState = CONFIGURED;

uint8_t g_USBModeFlag = 1;

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
void MX_FREERTOS_Init(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
void Delay_us(uint32_t num)
{
	uint16_t  differ = 0xffff-num-5;
	__HAL_TIM_SetCounter(&htim8,differ);
	HAL_TIM_Base_Start(&htim8);

  while( differ<0xffff-5)
  {
       differ = __HAL_TIM_GetCounter(&htim8);
  }

  HAL_TIM_Base_Stop(&htim8);
}

void HONG_CODE()
{
	if(Hong_Flag == 1)
	{
		if(Hong_Light == 0)
		{
			Hong_Light = 1;
			Full_COLOR(BAMBOO_GREEN);
			HAL_Delay(500);
			Full_COLOR(BLACK);
			Hong_Pre_flag = 2;
			Control_ID = 0;
			Common_ID = 0;
			Pre_index = 0;
			memset(Pre_ID,0,sizeof(Pre_ID));
			memset(Control_Code,0,sizeof(Control_Code));
			memset(Common_Code,0,sizeof(Common_Code));
		}
		if(BTK05_ATKeyDataPack[4] != 0)//控制按键部分
		{
			if((BTK05_ATKeyDataPack[4] & 0x01) == 0x01)//LCTRL
			{
				Control_Code[Control_ID] = 0x01;
				Control_ID++;
				if(tim3_Count_Time_Flag == 0)
				{
					tim3_Count_Time_Flag = 1;
					HAL_TIM_Base_Start_IT(&htim3);
					RGB_Set_Point(86,SKY);
				}
			}
			if((BTK05_ATKeyDataPack[4] & 0x02) == 0x02)//LSHIFT
			{
				Control_Code[Control_ID] = 0x02;
				Control_ID++;
				if(tim3_Count_Time_Flag == 0)
				{
					tim3_Count_Time_Flag = 1;
					HAL_TIM_Base_Start_IT(&htim3);
					RGB_Set_Point(63,SKY);
				}
			}
		  if((BTK05_ATKeyDataPack[4] & 0x04) == 0x04)//LALT
			{
				Control_Code[Control_ID] = 0x04;
				Control_ID++;
				if(tim3_Count_Time_Flag == 0)
				{
					tim3_Count_Time_Flag = 1;
					HAL_TIM_Base_Start_IT(&htim3);
					RGB_Set_Point(84,SKY);
				}
			}
			if((BTK05_ATKeyDataPack[4] & 0x08) == 0x08)//WIN
			{
				Control_Code[Control_ID] = 0x08;
				Control_ID++;
				if(tim3_Count_Time_Flag == 0)
				{
					tim3_Count_Time_Flag = 1;
					HAL_TIM_Base_Start_IT(&htim3);
					RGB_Set_Point(85,SKY);
				}
			}
			if((BTK05_ATKeyDataPack[4] & 0x10) == 0x10)//RCTRL
			{
				Control_Code[Control_ID] = 0x10;
				Control_ID++;
				if(tim3_Count_Time_Flag == 0)
				{
					tim3_Count_Time_Flag = 1;
					HAL_TIM_Base_Start_IT(&htim3);
					RGB_Set_Point(79,SKY);
				}
			}
			if((BTK05_ATKeyDataPack[4] & 0x20) == 0x20)//RSHIRT
			{
				Control_Code[Control_ID] = 0x20;
				Control_ID++;
				if(tim3_Count_Time_Flag == 0)
				{
					tim3_Count_Time_Flag = 1;
					HAL_TIM_Base_Start_IT(&htim3);
					RGB_Set_Point(74,SKY);
				}
			}
			if((BTK05_ATKeyDataPack[4] & 0x40) == 0x40)//RALT
			{
				Control_Code[Control_ID] = 0x40;
				Control_ID++;
				if(tim3_Count_Time_Flag == 0)
				{
					tim3_Count_Time_Flag = 1;
					HAL_TIM_Base_Start_IT(&htim3);
					RGB_Set_Point(82,SKY);
				}
			}
		}
		for(int index = 0;index < Control_ID - 1;index++)
		{
			if(Control_Code[index] == Control_Code[Control_ID - 1])
			{
				Control_Code[Control_ID - 1] = 0;
				Control_ID--;
				break;
			}
		}
		for(int index = 0;index < 6;index++)//常规按键部分
		{
			if(BTK05_ATKeyDataPack[6+index] != 0)
			{
				Common_Code[Common_ID] = BTK05_ATKeyDataPack[6+index];
				Common_ID++;
				if(tim3_Count_Time_Flag == 0)
				{
					tim3_Count_Time = 1;
					HAL_TIM_Base_Start_IT(&htim3);
					for(int i = 0;i < 5;i++)
					{
						for(int index = 0;index < 16;index++)
						{
							if(Common_Code[Common_ID-1] == sequence_1[i][index])
							{
								RGB_Set_Point_Row(i,index,SKY);
							}
						}
					}
				}
			}
		}

		for(int index = 0;index < Common_ID - 1;index++)
		{
			if(Common_Code[index] == Common_Code[Common_ID-1])
			{
				Common_Code[Common_ID - 1] = 0;
				Common_ID--;
				break;
			}
		}

	}


	if(Hong_Flag == 2 && Hong_Pre_flag == 2)
	{
		for(int index = 0;index < 8;index++)//控制按键解算
		{
			Control_BUTTON |= Control_Code[index];
		}
		Send_1[0] = Control_BUTTON;
		for(int index = 2;index < 7;index++)
		{
			Send_1[index] = Common_Code[index-2];
		}
		if(Hong_Light == 1)
		{
			Hong_Light = 0;
			Full_COLOR(LIGHT_PURPLE);
			HAL_Delay(500);
			Full_COLOR(RGB_STATE);
		}
		Hong_Pre_flag = 1;
		Hong_Flag = 0;
	}
	if(Hong_Flag == 3 && Hong_Pre_flag == 2)
	{
		for(int index = 0;index < 8;index++)
		{
			Control_BUTTON |= Control_Code[index];
		}
		Send_2[0] = Control_BUTTON;
		for(int index = 2;index < 8;index++)
		{
			Send_2[index] = Common_Code[index-2];
		}
		if(Hong_Light == 1)
		{
			Hong_Light = 0;
			Full_COLOR(LIGHT_PURPLE);
			HAL_Delay(500);
			Full_COLOR(RGB_STATE);
		}
		Hong_Pre_flag = 1;
		Hong_Flag = 0;
	}
}

void Light_Function()
{
	Choose_Color();
	Water_Flow_ROW(RGB_STATE);
	Water_Flow_COL(RGB_STATE);
	Breath(RGB_STATE);
	Point_Water_Independent(RGB_STATE);
}

//宏输出
void COPY_PASTE(uint8_t* First,uint8_t* Second)
{
	if(COPY_PASTE_flag == ON)//如果当前宏输出模式开启
	{
		if(Light_Flag == OFF)//如果当前灯闪烁状态为关闭状态
		{
			Right_Flag = UNACTIVATED;
			Left_Flag = UNACTIVATED;
			Light_Flag = ACTIVATED;
			Full_COLOR(DEEP_PINK);
			osDelay(500);
			Full_COLOR(RGB_STATE);
			Pre_flag = 2;
		}

		if(HAL_GPIO_ReadPin(RIGHT_GPIO_Port,RIGHT_Pin) == 1 && Left_Flag == 0 && Right_Flag == 0)
		{
			Right_Flag = ACTIVATED;
		}
		if(HAL_GPIO_ReadPin(LEFT_GPIO_Port,LEFT_Pin) == 1 && Left_Flag == 0 && Right_Flag == 0)
		{
			Left_Flag = ACTIVATED;
		}
		if(HAL_GPIO_ReadPin(RIGHT_GPIO_Port,RIGHT_Pin) == 1 && Left_Flag == 1)
		{
			if(g_USBModeFlag == 1)//如果现在为直连状态
			{
				USBD_CUSTOM_HID_SendReport(&hUsbDeviceFS,First,8);
				while(HAL_GPIO_ReadPin(RIGHT_GPIO_Port,RIGHT_Pin) == 1);
				USBD_CUSTOM_HID_SendReport(&hUsbDeviceFS,blank,8);
				Left_Flag = UNACTIVATED;
			}
			else//现在为蓝牙连接状态
			{
				for(int index = 4;index < 12;index++)//拷贝数组
				{
					Blue_tooth_Buffer[index] = First[index - 4];
				}
				BTK05_UART_SendKeyData(Blue_tooth_Buffer,12);
				while(HAL_GPIO_ReadPin(RIGHT_GPIO_Port,RIGHT_Pin) == 1);
				for(int index = 4;index < 12;index++)
				{
					Blue_tooth_Buffer[index] = blank[index - 4];
				}
        BTK05_UART_SendKeyData(Blue_tooth_Buffer,12);
				Left_Flag = UNACTIVATED;
			}
		}
		if(HAL_GPIO_ReadPin(LEFT_GPIO_Port,LEFT_Pin) == 1 && Right_Flag == 1)
		{
			if(g_USBModeFlag == 1)//如果现在为直连状态
			{
				USBD_CUSTOM_HID_SendReport(&hUsbDeviceFS,Second,8);
				while(HAL_GPIO_ReadPin(LEFT_GPIO_Port,LEFT_Pin) == 1);
				USBD_CUSTOM_HID_SendReport(&hUsbDeviceFS,blank,8);
				Right_Flag = UNACTIVATED;
			}
			else//现在为蓝牙连接状态
			{
				for(int index = 4;index < 12;index++)//拷贝数组
				{
					Blue_tooth_Buffer[index] = Second[index - 4];
				}
				BTK05_UART_SendKeyData(Blue_tooth_Buffer,12);
				while(HAL_GPIO_ReadPin(LEFT_GPIO_Port,LEFT_Pin) == 1);
				for(int index = 4;index < 12;index++)
				{
					Blue_tooth_Buffer[index] = blank[index - 4];
				}
				BTK05_UART_SendKeyData(Blue_tooth_Buffer,12);
				Right_Flag = UNACTIVATED;
			}
		}

		if(count_time_1s_left >= 5)//如果时间过长，两端清零
		{
			Left_Flag = UNACTIVATED;
			Right_Flag = UNACTIVATED;
			count_time_1s_left = 0;
		}
		if(count_time_1s_right >= 5)//如果时间过长，两端清零
		{
			Left_Flag = UNACTIVATED;
			Right_Flag = UNACTIVATED;
			count_time_1s_right = 0;
		}
	}


	if(COPY_PASTE_flag == OFF && Pre_flag == 2)//
	{
		if(Light_Flag == ACTIVATED)
		{
			Light_Flag = UNACTIVATED;
			Full_COLOR(ORANGE);
			osDelay(500);
			Full_COLOR(RGB_STATE);
		}
		Pre_flag = 1;
	}
}

void Final_Function()
{
	if(g_USBModeFlag == 1)//当标志为1时，是USB直连模式
	{
		if(sleepTime1SCounter <= 1000)
		{
			myKeyBoard_ScanKeyAndUpdataATBuffer();//键盘事件更新
			if(g_myKeyBoard_DataWaitForUploadFlag == 1)
			{
				sleepTime1SCounter = 0;
				g_myKeyBoard_DataWaitForUploadFlag = 0;
				if(bDeviceState == CONFIGURED && Hong_Flag == 0)
				{
					USBD_CUSTOM_HID_SendReport(&hUsbDeviceFS,&BTK05_ATKeyDataPack[4],8);
				}
			}
		}
		else if(system_Status == 0)//处于休眠模式
		{
			myKeyBoard_ScanKeyAndUpdataATBuffer();
			if(g_myKeyBoard_DataWaitForUploadFlag == 1)//如果键盘数据发生更新
			{
				g_myKeyBoard_DataWaitForUploadFlag = 0;
				if(bDeviceState == CONFIGURED && Hong_Flag == 0)
				{
					USBD_CUSTOM_HID_SendReport(&hUsbDeviceFS,&BTK05_ATKeyDataPack[4],8);
				}

				//计时器使�?
				HAL_TIM_Base_Start_IT(&htim2);

				system_Status = 1;
				sleepTime1SCounter = 0;
				//唤醒LED
				if(Color_Flag != LIGHT_COLOR_STATE)
				{
					Color_Flag = LIGHT_COLOR_STATE;
					RGB_STATE = RGB_STATE_PRE;
					Full_COLOR(RGB_STATE);
				}
			}
		}
		else if(sleepTime1SCounter > 1000)
		{
			//休眠代码
			HAL_TIM_Base_Stop_IT(&htim2);
			system_Status = 0;
			//休眠LED
			if(Color_Flag != BLACK_COLOR_STATE)
			{
				Full_COLOR(BLACK);
				Color_Flag = BLACK_COLOR_STATE;
				RGB_STATE_PRE = RGB_STATE;
				RGB_STATE = BLACK;
			}
		}
	}

	else//蓝牙模式
	{
		//如果键盘休眠计时<=400秒且蓝牙醒着
		if(sleepTime1SCounter <= 40000 && BTK05_Status == BTK_WAKE)
		{
			myKeyBoard_ScanKeyAndUpdataATBuffer();//键盘事件更新
			if(g_myKeyBoard_DataWaitForUploadFlag == 1 && Hong_Flag == 0)
			{
				g_myKeyBoard_DataWaitForUploadFlag = 0;
				BTK05_UART_SendKeyData(BTK05_ATKeyDataPack,12);
				sleepTime1SCounter = 0;
			}
		}
		else if(BTK05_Status == BTK_SLEEP)//如果蓝牙处于休眠模式
		{
			myKeyBoard_ScanKeyAndUpdataATBuffer();
			if(g_myKeyBoard_DataWaitForUploadFlag == 1 && Hong_Flag == 0)
			{
				system_Status = 1;
				BTK05_Wake();
				//使能计时�?
				HAL_TIM_Base_Start_IT(&htim2);
				sleepTime1SCounter = 0;
				g_myKeyBoard_DataWaitForUploadFlag = 0;
				BTK05_UART_SendKeyData(BTK05_ATKeyDataPack,12);
			}
			if(Color_Flag != LIGHT_COLOR_STATE)
			{
				Color_Flag = LIGHT_COLOR_STATE;
				RGB_STATE = RGB_STATE_PRE;
				Full_COLOR(RGB_STATE);
			}
		}
		else if(sleepTime1SCounter > 40000)//蓝牙进入休眠模式
		{
			BTK05_Sleep();
			//关闭TIM
			HAL_TIM_Base_Stop_IT(&htim2);
			system_Status = 0;
			//关闭LED
			if(Color_Flag != BLACK_COLOR_STATE)
			{
				Full_COLOR(BLACK);
				Color_Flag = BLACK_COLOR_STATE;
				RGB_STATE_PRE = RGB_STATE;
				RGB_STATE = BLACK;
			}
		}
	}
}


/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_TIM8_Init();
  MX_USART1_UART_Init();
  MX_TIM2_Init();
  MX_TIM1_Init();
  MX_TIM3_Init();
  /* USER CODE BEGIN 2 */
	//唤醒BTK05
	//BTK05_Wake();
	HAL_TIM_Base_Start_IT(&htim2);
	HAL_GPIO_WritePin(BUZZ_GPIO_Port,BUZZ_Pin,0);
  /* USER CODE END 2 */

  /* Call init function for freertos objects (in freertos.c) */
  MX_FREERTOS_Init();

  /* Start scheduler */
  osKernelStart();

  /* We should never get here as control is now taken by the scheduler */
  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */

  }

  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USB;
  PeriphClkInit.UsbClockSelection = RCC_USBCLKSOURCE_PLL_DIV1_5;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */
//int fputc(int ch, FILE *f)
//{
//    HAL_UART_Transmit(&huart3, (unsigned char *)&ch, 1, 0xFFFF);
//    return ch;
//}
/* USER CODE END 4 */

/**
  * @brief  Period elapsed callback in non blocking mode
  * @note   This function is called  when TIM4 interrupt took place, inside
  * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
  * a global variable "uwTick" used as application time base.
  * @param  htim : TIM handle
  * @retval None
  */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  /* USER CODE BEGIN Callback 0 */

  /* USER CODE END Callback 0 */
  if (htim->Instance == TIM4) {
    HAL_IncTick();
  }
  /* USER CODE BEGIN Callback 1 */

  /* USER CODE END Callback 1 */
}

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
